from Utility_Http import Http
from pyquery import PyQuery as PythonQuery
from JCI_Config import *
import time


def get_jci_column_len():
    return len(list_api_url)


def get_jci_column():
    return get_col_data()


def get_jci_web_content(url):
    http_obj = Http(url)
    html_doc = http_obj.get().text
    return {
        'web_content': html_doc
    }


def get_jci_contents(news_col, news_id):
    http_obj = Http(get_content_api_url(news_col, news_id))
    html_doc = PythonQuery(http_obj.get().text)
    html_doc.make_links_absolute(base_url)
    news_title = html_doc('#web2l form h1').text()
    news_date_time = html_doc('#web2l form h3').text()[3:14].replace('年', '-').replace('月', '-').replace('日', '')
    news_content = html_doc('.v_news_content').html()
    news_attach_list = html_doc('#web2l>form>div>ul>li')
    news_attaches = []
    tmp_src = html_doc('.v_news_content img').attr.src
    news_thumb = tmp_src if tmp_src is not None else ''
    for attach_item in news_attach_list.items():
        news_attaches.append({
            'attach_url': attach_item.find('a').attr.href,
            'attach_name': attach_item.text().split('已下载')[0]
        })
    return {
        'title': news_title,
        'date_time': news_date_time,
        'timestamp': int(time.mktime(time.strptime(news_date_time, "%Y-%m-%d"))),
        'news_content': news_content,
        'news_attaches': news_attaches,
        'thumb': news_thumb
    }


def get_jci_news(column_id=0):
    http_obj = Http(list_api_url[column_id].get('url'))
    html_doc = PythonQuery(http_obj.get().text)
    html_doc.make_links_absolute(base_url)
    html_data = html_doc('.list-con ul li a')
    news_data = []
    for news_item in html_data.items():
        news_links = news_item.attr.href.split('/')
        news_col = 0
        news_id = 0
        if len(news_links) == 6:
            news_col = news_links[4]
            news_id = news_links[5].split('.')[0]
        tmp_news_data = {
            'absolute_url': news_item.attr.href,
            'news_col': news_col,
            'news_id': news_id,
            'title': news_item.attr.title,
            'timestamp': int(time.mktime(time.strptime(str(news_item.text())[:10], "%Y-%m-%d")))
        }
        news_data.append(tmp_news_data)
    return {
        'column_title': list_api_url[column_id].get('title'),
        'total': len(news_data),
        'list': news_data
    }
